package org.halk.util;


import cn.hutool.core.date.DateUtil;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamResolution;
import org.halk.config.ApplicationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @Author halk
 * @Date 2024/6/6 下午2:01
 **/
@Component
public class CameraUtil {

    @Resource
    private ApplicationProperties applicationProperties;


    /**
     * 获取实时图像
     * @return
     */
    public File getRealTimeImage() {
        Webcam webcam = null;

        File file = new File(applicationProperties.getFolder());
        if (!file.exists()) {
            file.mkdirs();
        }

        // 指定输出文件路径
        String format = DateUtil.format(new Date(), "yyyyMMdd-HHmmss");
        String outputPath = applicationProperties.getFolder() + format + ".png";
        File outputFile = new File(outputPath);

        try {
            // 获取并打开摄像头
            webcam = Webcam.getDefault();
            // 设置摄像头分辨率（可选）
            webcam.setViewSize(WebcamResolution.VGA.getSize());
            webcam.open();
            // 获取摄像头图像
            BufferedImage image = webcam.getImage();

            try {
                // 写入 PNG 图像，第二个参数是格式名称，"PNG" 对应 PNG 文件
                ImageIO.write(image, "PNG", outputFile);
                System.out.println("Image saved successfully as PNG.");
            } catch (IOException e) {
                System.err.println("Error saving the image: " + e.getMessage());
            }

        } catch (Exception e) {
            System.err.println("Error accessing webcam: " + e.getMessage());
        } finally {
            // 确保摄像头在程序结束时被关闭
            if (webcam != null && webcam.isOpen()) {
                webcam.close();
            }
        }

        return outputFile;
    }


    public void saveCamera() {
        System.out.println("Hello world!");

        WebcamPanel panel = null;
        Webcam webcam = null;
        try {
            // 获取并打开摄像头
            webcam = Webcam.getDefault();
            // 设置摄像头分辨率（可选）
            webcam.setViewSize(WebcamResolution.VGA.getSize());
            webcam.open();

            // 创建WebcamPanel来显示摄像头画面
            panel = new WebcamPanel(webcam);
            // 是否显示帧率
            panel.setFPSDisplayed(true);
            // 是否显示调试信息
            panel.setDisplayDebugInfo(true);

             //创建一个JFrame窗口来放置摄像头画面
            JFrame frame = new JFrame("Webcam Viewer");
            frame.add(panel);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
            // 设置窗口大小
            frame.setSize(new Dimension(640, 480));

            // 指定输出文件路径
            String path = "E:/camera/loop/";
            while (true) {
                // 获取摄像头图像
                BufferedImage image = webcam.getImage();

                // 指定输出文件路径
                String format = DateUtil.format(new Date(), "yyyyMMdd-HHmmss");
                String outputPath = path + format + ".png";
                File outputFile = new File(outputPath);

                try {
                    // 写入 PNG 图像，第二个参数是格式名称，"PNG" 对应 PNG 文件
                    ImageIO.write(image, "PNG", outputFile);
                    System.out.println("Image saved successfully as " + outputPath);
                } catch (IOException e) {
                    System.err.println("Error saving the image: " + e.getMessage());
                }

                // 刷新窗口以显示最新图像
                panel.repaint();
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            System.err.println("Error accessing webcam: " + e.getMessage());
        } finally {
            // 确保摄像头在程序结束时被关闭
            if (webcam != null && webcam.isOpen()) {
                webcam.close();
            }
        }
    }


    public static void main(String[] args) {
        new CameraUtil().saveCamera();
    }
}
